package cn.frontop.funswitch.enums;

import cn.frontop.funswitch.entity.RequestDto;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;

/**
 * @author Yun
 */
@SuppressWarnings({"AlibabaEnumConstantsMustHaveComment", "unchecked"})
public enum RequestEnum {
    GET {
        @Override
        public String conversion(RequestDto dto) {
            return HttpRequest.get(dto.getUrl())
                    .headerMap(toMapString(JSONUtil.toBean(dto.getHeaders(), HashMap.class)), true)
                    .body(dto.getBody())
                    .timeout(30000)
                    .execute()
                    .body();
        }
    }, POST {
        @Override
        public String conversion(RequestDto dto) {
            return HttpRequest.post(dto.getUrl())
                    .headerMap(toMapString(JSONUtil.toBean(dto.getHeaders(), HashMap.class)), true)
                    .body(dto.getBody())
                    .timeout(30000)
                    .execute()
                    .body();
        }
    }, PUT {
        @Override
        public String conversion(RequestDto dto) {
            return HttpRequest.put(dto.getUrl())
                    .headerMap(toMapString(JSONUtil.toBean(dto.getHeaders(), HashMap.class)), true)
                    .body(dto.getBody())
                    .timeout(30000)
                    .execute()
                    .body();
        }
    }, DELETE {
        @Override
        public String conversion(RequestDto dto) {
            return HttpRequest.delete(dto.getUrl())
                    .headerMap(toMapString(JSONUtil.toBean(dto.getHeaders(), HashMap.class)), true)
                    .body(dto.getBody())
                    .timeout(30000)
                    .execute()
                    .body();
        }
    };

    @SuppressWarnings({"rawtypes", "UnnecessaryLocalVariable"})
    private static HashMap<String, String> toMapString(HashMap hashMap) {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        hashMap.keySet().forEach(t -> stringStringHashMap.put(t.toString(), hashMap.get(t).toString()));
        return stringStringHashMap;
    }

    /**
     * 转换工厂
     *
     * @param dto 数据
     * @return 结果
     */
    public abstract String conversion(RequestDto dto);
}
